package org.yang.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.yang.reggie.common.R;
import org.yang.reggie.dto.SetmealDto;
import org.yang.reggie.entity.Category;
import org.yang.reggie.entity.Setmeal;
import org.yang.reggie.service.CategoryService;
import org.yang.reggie.service.SetmealDishService;
import org.yang.reggie.service.SetmealService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 缘友一世
 * date 2023/5/14-15:37
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息：{}",setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name) {
        //分页构造器对象
        Page<Setmeal> pageInfo=new Page<>(page,pageSize);
        Page<SetmealDto> pageDtoInfo=new Page<>(page,pageSize);

        //查询条件和排序条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //根据更新时间降序排序
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);

        //对象拷贝 由于泛型类型（实体类不一样），所以需要忽略records，手动拷贝
        BeanUtils.copyProperties(pageInfo,pageDtoInfo,"records");

        List<SetmealDto> setmealDtoList=null;

        List<Setmeal> records = pageInfo.getRecords();
        //item为遍历出来的每一个Setmeal实体
        setmealDtoList=records.stream().map((item)->{
            //新建需要封装的SetmealDto 然后再分别赋值：categoryName和其他属性
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            //根据分类id 查询分类名称
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category!=null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        //将setmealDtoList封装到pageDtoInfo
        pageDtoInfo.setRecords(setmealDtoList);

        return R.success(pageDtoInfo);
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除套餐：ids:{}",ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 修改套餐的售出状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<List<Setmeal>> getStatus(@PathVariable("status") int status, @RequestParam("ids") List<String> ids) {
        List<Setmeal> list = new ArrayList<>();
        for (String id : ids) {
            Setmeal setmeal = setmealService.getById(Long.valueOf(id));
            if (setmeal != null) {
                setmeal.setStatus(status);
                setmealService.updateById(setmeal);
                list.add(setmeal);
            }
        }
        return R.success(list);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getDish(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息
     * @param setmealDto
     * @return
     */
    @PutMapping()
    @CacheEvict(value = "setmealCache", key = "#setmealDto.categoryId+'_'+#setmealDto.status")
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        //log.info(setmealDto.toString());
        setmealService.updateWithdish(setmealDto);
        return R.success("修改套餐成功");
    }

    /**
     * 移动端根据条件查询套餐
     * @return
     * 注意
     *          @RequestBody 接收json格式的数据
     *          如果是通过键值对传递，直接使用实体类接收即可
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key="#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal ) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }

}
